package com.java.demo.thread;

/**
 * 同步demo
 *
 * @auther zhangwj
 * @date 2020/4/8 1:58 下午
 */
public class DemoSynchronized {

    public static void main(String[] args) {
        Server server = new Server();
        MyThread1 myThread1 = new MyThread1(server);
        myThread1.setName("Thread A");
        MyThread2 myThread2 = new MyThread2(server);
        myThread2.setName("Thread B");
        myThread2.start();
        myThread1.start();
    }
}


class Server {

    public void log() throws InterruptedException {
        System.out.println("-------线程名称:" + Thread.currentThread().getName() + " server log start-------");
        Thread.sleep(5000);
        synchronized (this) {
            System.out.println("-------线程名称:" + Thread.currentThread().getName() + " server log end-------");
        }
    }

    public void outLog() throws InterruptedException {
        System.out.println("-------线程名称:" + Thread.currentThread().getName() + " server outLog start-------");
        Thread.sleep(1000);
        System.out.println("-------线程名称:" + Thread.currentThread().getName() + " server outLog end-------");
    }
}

class MyThread1 extends Thread {

    private Server server;

    MyThread1(Server server) {
        super();
        this.server = server;
    }

    @Override
    public void run() {
        super.run();
        try {
            server.outLog();
            server.log();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

class MyThread2 extends Thread {

    private Server server;

    MyThread2(Server server) {
        super();
        this.server = server;
    }

    @Override
    public void run() {
        super.run();
        try {
            server.outLog();
            server.log();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}